
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>当springMVC上下文尚未初始化的时候如何@Autowired注入对象呢？ - Luis Blog</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="Luis,"> 
    <meta name="description" content="java开发工程师，喜欢代码，喜欢技术,
一个问题困扰了我一天，场景是这样的：

公司有一个独立的SSO用户权限验证中心，我负责的是公司的一个其他的独立项目；
每次用户session过期或者未登录的时候跳统一登录页面；
用户成功登录之后都,"> 
    <meta name="author" content="winter chen"> 
    <link rel="alternative" href="atom.xml" title="Luis Blog" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    
    
<link rel="stylesheet" href="/css/diaspora.css">

	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <script>
         (adsbygoogle = window.adsbygoogle || []).push({
              google_ad_client: "ca-pub-8691406134231910",
              enable_page_level_ads: true
         });
    </script>
    <script async custom-element="amp-auto-ads"
        src="https://cdn.ampproject.org/v0/amp-auto-ads-0.1.js">
    </script>
<meta name="generator" content="Hexo 4.2.0"></head>

<body class="loading">
    <span id="config-title" style="display:none">Luis Blog</span>
    <div id="loader"></div>
    <div id="single">
    <div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <a class="iconfont icon-home image-icon" href="javascript:;" data-url="https://blog.winterchen.com"></a>
    <div title="播放/暂停" class="iconfont icon-play"></div>
    <h3 class="subtitle">当springMVC上下文尚未初始化的时候如何@Autowired注入对象呢？</h3>
    <div class="social">
        <div>
            <div class="share">
                <a title="获取二维码" class="iconfont icon-scan" href="javascript:;"></a>
            </div>
            <div id="qr"></div>
        </div>
    </div>
    <div class="scrollbar"></div>
</div>

    <div class="section">
        <div class="article">
    <div class='main'>
        <h1 class="title">当springMVC上下文尚未初始化的时候如何@Autowired注入对象呢？</h1>
        <div class="stuff">
            <span>五月 30, 2018</span>
            
  <ul class="post-tags-list" itemprop="keywords"><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/spring/" rel="tag">spring</a></li></ul>


        </div>
        <div class="content markdown">
            <p><img src="http://img.winterchen.com/rawpixel-586687-unsplash.jpg" alt=""></p>
<p>一个问题困扰了我一天，场景是这样的：</p>
<ul>
<li>公司有一个独立的SSO用户权限验证中心，我负责的是公司的一个其他的独立项目；</li>
<li>每次用户session过期或者未登录的时候跳统一登录页面；</li>
<li>用户成功登录之后都会回调，回调的信息中有用户的userAccount；</li>
<li>此时需要根据用户的userAccount获取用户的详细信息；</li>
<li>权限系统提供了一个获取用户的接口；<a id="more"></a>

</li>
</ul>
<p>遇到的问题：</p>
<ul>
<li>使用的是shrio进行系统权限的控制，当用户在SSO登录页面成功登录之后会回调到shrio的配置类中；</li>
<li>需要在shrio的配置类中调用根据用户账号获取用户信息的接口：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IecWepmShiroAuthService</span> <span class="keyword">extends</span> <span class="title">AbstractShiroAuthService</span>&lt;<span class="title">SessionUser</span>&gt; <span class="keyword">implements</span> <span class="title">EnvironmentAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TenantUserCloudService tenantUserCloudService;</span><br><span class="line">&#125;</span><br><span class="line">```	</span><br><span class="line"></span><br><span class="line">调用的就是这么一个接口</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line"><span class="meta">@CloudServiceClient</span>(<span class="string">"gap-service-tenant-auth"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">TenantUserCloudService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@RequestMapping</span>(</span><br><span class="line">        value = &#123;<span class="string">"/tenant/user/by-emp-no"</span>&#125;,</span><br><span class="line">        method = &#123;RequestMethod.GET&#125;</span><br><span class="line">    )</span><br><span class="line">    <span class="function">APIResponse&lt;TenantUser&gt; <span class="title">getTenantUserByEmpNo</span><span class="params">(@RequestParam(name = <span class="string">"tenantId"</span>,required = <span class="keyword">true</span>)</span> Integer var1, @<span class="title">RequestParam</span><span class="params">(name = <span class="string">"empNo"</span>,required = <span class="keyword">true</span>)</span> String var2)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果按照下面的代码进行注入，那么由于shrio的初始化要先与springMVC，所以导致找不到相关处理的类；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TenantUserCloudService tenantUserCloudService;</span><br></pre></td></tr></table></figure>

<p>解决的思路就是：</p>
<ul>
<li>首先不进行<code>tenantUserCloudService</code>的初始化，只有在调用该接口的时候进行初始化；</li>
<li>创建一个类实现<code>ApplicationContextAware</code>接口，实现这个接口可以很方便的从spring容器中获取bean；</li>
<li>机制就是<strong>当调用这个接口的时候才从spring容器中获取这个bean</strong>；</li>
</ul>
<p>创建一个类实现<code>ApplicationContextAware</code>接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//相当于给一个bean进行代理</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DelegateBean</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(DelegateBean.class);</span><br><span class="line">    <span class="keyword">protected</span> ApplicationContext applicationContext;</span><br><span class="line">    <span class="keyword">protected</span> Object target;</span><br><span class="line">    <span class="keyword">protected</span> String targetBeanName;</span><br><span class="line">    <span class="keyword">protected</span> Class targetBeanType;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DelegateBean</span><span class="params">(String targetBeanName)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.targetBeanName = targetBeanName;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DelegateBean</span><span class="params">(Class targetBeanType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.targetBeanType = targetBeanType;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DelegateBean</span><span class="params">(ApplicationContext applicationContext, String targetBeanName)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.applicationContext = applicationContext;</span><br><span class="line">        <span class="keyword">this</span>.targetBeanName = targetBeanName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DelegateBean</span><span class="params">(ApplicationContext applicationContext, Class targetBeanType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.applicationContext = applicationContext;</span><br><span class="line">        <span class="keyword">this</span>.targetBeanType = targetBeanType;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.applicationContext = applicationContext;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//当调用这个方法的时候才从spring容器中获取bean；</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">target</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Assert.notNull(<span class="keyword">this</span>.applicationContext, <span class="string">"A DelegateBean should be managed by ApplicationContext or pass ApplicationContext though constructor arg"</span>);</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.target == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span>(<span class="keyword">this</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.target != <span class="keyword">null</span>?<span class="keyword">this</span>.target:(<span class="keyword">this</span>.target = <span class="keyword">this</span>.doGetBeanFromApplicationContext());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.target;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">doGetBeanFromApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.targetBeanName != <span class="keyword">null</span>?<span class="keyword">this</span>.applicationContext.getBean(<span class="keyword">this</span>.targetBeanName):(<span class="keyword">this</span>.targetBeanType != <span class="keyword">null</span>?<span class="keyword">this</span>.applicationContext.getBean(<span class="keyword">this</span>.targetBeanType):<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>只是这样配置还是不够的，我们需要在spring初始化的时候将这个代理bean交给spring容器进行管理；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IecWepmAutoConfiguration</span></span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Qualifier</span>(<span class="string">"tenantUserCloudService"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> DelegateBean <span class="title">tenantUserCloudService</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DelegateBean(TenantUserCloudService.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后再shrio的类中我们需要进行这样的使用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IecWepmShiroAuthService</span> <span class="keyword">extends</span> <span class="title">AbstractShiroAuthService</span>&lt;<span class="title">SessionUser</span>&gt; <span class="keyword">implements</span> <span class="title">EnvironmentAware</span> </span>&#123;</span><br><span class="line">	<span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@Qualifier</span>(<span class="string">"tenantUserCloudService"</span>)</span><br><span class="line">    <span class="keyword">private</span> DelegateBean tenantUserCloudService;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SessionUser <span class="title">doLogin</span><span class="params">(String userAccount, String userPwd)</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//根据用户编号获取用户信息,调用target()是关键，只有在调用这个方法的时候才会从spring容器中获取信息</span></span><br><span class="line">        APIResponse&lt;TenantUser&gt; tenantUserByEmpNo = ((TenantUserCloudService) tenantUserCloudService.target())</span><br><span class="line">                .getTenantUserByEmpNo(TENANT_ID, userAccount);</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">"success"</span>.equals(tenantUserByEmpNo.getCode()) &amp;&amp; <span class="keyword">null</span> != tenantUserByEmpNo.getData())&#123;</span><br><span class="line">            userAccount = tenantUserByEmpNo.getData().getDomainAccountList().get(<span class="number">0</span>).getDomainAccount();</span><br><span class="line">        &#125;</span><br><span class="line">        UserInfoDto userInfo = userService.getUserByAccount(userAccount);</span><br><span class="line">        SessionUser sessionUser = <span class="keyword">new</span> SessionUser();</span><br><span class="line">        sessionUser.setUserId(Integer.valueOf(userAccount));</span><br><span class="line">        AuthUtils.setSessionUser(sessionUser);</span><br><span class="line">        <span class="comment">// todo 返回的SessionUser 就是保存在session里的对象 通过 SessionUser sessionUser = (SessionUser) AuthUtils.getSessionUser(); 进行获取</span></span><br><span class="line">        <span class="keyword">return</span> sessionUser;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>关键： <strong>以上的思路最主要的就是，在shrio初始化的时候仅仅只是初始化一个空壳，只有当使用那个bean的时候才从spring容器中获取bean并且注入，这样的好处就是当当前bean的声明周期还未开始的时候预留一个位置，当使用的时候才从spring容器中注入，这样不会导致项目启动的时候就会找不到bean</strong>；</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls" data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
                <ul id="audio-list" style="display:none">
                    
                        
                            <li title='0' data-url='https://raw.githubusercontent.com/WinterChenS/imgrpo/master/mp3/%E6%96%B0%E8%A3%A4%E5%AD%90-%E7%94%9F%E6%B4%BB%E5%9B%A0%E4%BD%A0%E8%80%8C%E7%81%AB%E7%83%AD.mp3'></li>
                        
                    
                </ul>
            
        </div>
        
    <div id='gitalk-container' class="comment link"
		data-enable='false'
        data-ae='false'
        data-ci='77f2adc33e0112d086d7'
        data-cs='e926aa3a621556609b2c2b76d89320fa524e23cd'
        data-r='WinterChenS.github.io'
        data-o='WinterChenS'
        data-a='WinterChenS'
        data-d='false'
    >查看评论</div>


    </div>
    
</div>


    </div>
</div>
</body>


<script src="//lib.baomitu.com/jquery/1.8.3/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/typed.js"></script>
<script src="/js/diaspora.js"></script>


<link rel="stylesheet" href="/photoswipe/photoswipe.css">
<link rel="stylesheet" href="/photoswipe/default-skin/default-skin.css">


<script src="/photoswipe/photoswipe.min.js"></script>
<script src="/photoswipe/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>





<!-- Google Analytics -->
<script type="text/javascript">
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'G-30C04D6TMS', 'auto');
  ga('send', 'pageview');
</script>
<!-- End Google Analytics -->


</html>
